package com.l.web.service.webcontent;

import com.l.web.service.ResponseCode;
import com.l.web.service.system.webnode.WebNodeDAO;
import com.l.web.service.system.webnode.WebNodeOption;
import com.l.web.service.system.webnode.WebNodeOptionDAO;
import org.l.qiao.ClusterUtil;
import org.l.qiao.Validate;
import org.l.qiao.search.Query;
import org.l.qiao.search.Sort;
import com.l.web.service.ResponseInfo;
import com.l.web.service.ServiceSupport;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class WebContentAddService extends ServiceSupport {

    private static final Logger LOGGER = Logger.getLogger(WebContentAddService.class);
    private WebContentDAO webContentDAO;
    private WebNodeDAO webNodeDAO;
    private WebNodeOptionDAO webNodeOptionDAO;
    private String type = "";
    private WebContent webContent = new WebContent();

    public void setWebContentDAO(WebContentDAO webContentDAO) {
        this.webContentDAO = webContentDAO;
    }

    public void setWebNodeDAO(WebNodeDAO webNodeDAO) {
        this.webNodeDAO = webNodeDAO;
    }

    public void setWebNodeOptionDAO(WebNodeOptionDAO webNodeOptionDAO) {
        this.webNodeOptionDAO = webNodeOptionDAO;
    }

    public String execute() {
        String type = form.getString(TYPE);
        switch (type) {
            case "save":
                return save();
            default:
                return add();
        }
    }

    private String add() {
        String webNodeId = form.getString("webNodeId");
        List webNodeOptions =new ArrayList();

        if (Validate.check(Validate.OBJECTID, webNodeId)) {
            Query query = new Query();
            query.idEQ(WebNodeOption.WEB_NODE_ID, webNodeId);
            Sort sort = new Sort();
            sort.asc(WebNodeOption.INDEX);
            webNodeOptions = webNodeOptionDAO.find(query, null, sort);
        }

        context.put("webNodeOptions", webNodeOptions);
        context.put("webNodeId", webNodeId);
        context.put("check", ClusterUtil.getCheck(WebContent.class));
        return ADD;
    }

    private String save() {
        boolean check = form.getCluster(webContent);
        LOGGER.debug("添加栏目内容信息：" + webContent);
        if (check) {
            ResponseInfo rj = new ResponseInfo();
            String id = webContent.setId();
            webContent.put(WebContent.CREATED, new Date());
            webContent.initWebNodeId();
            webContentDAO.insert(webContent);
            rj.setCode(ResponseCode.FINISH);
            rj.put("id", id);
            out(rj);
        } else {
            error(404);
            LOGGER.error("非法添加栏目内容信息：" + webContent);
        }
        return NONE;
    }

}
